package com.kws.system.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <b>OkHttpUtil</b>
 *
 * @description: OkHttpUtil <br>
 * @date: 2024/11/11 14:41 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */
public class OkHttpUtil {
    /**
     * 发送http请求
     * @param requestUrl
     * @return
     */
    public static Object sendOkHttpClient(String requestUrl, String requestMethod, RequestBody body, Map<String, String> headers){
        if(headers == null){
            headers = new HashMap<>();
        }
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(30, TimeUnit.SECONDS) // 读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS) // 写入超时时间
                .build();
        Request request = new Request.Builder()
                .url(requestUrl)
                .method(requestMethod, body != null ? body : null)
                .headers(Headers.of(headers))
                .build();
        try (Response response = client.newCall(request).execute()) { // 使用 try-with-resources 确保自动关闭响应体
            if (response.isSuccessful()) {
                System.out.println(response.header("X-Bce-Request-Id"));
                return response.body().string();
            } else {
                String errorMessage = response.header("X-Bce-Error-Message");
                String requestId = response.header("X-Bce-Request-Id");
                System.out.println("Request failed: " + response.code() + " - "
                        + response.message() + " - " + errorMessage + " - " + requestId);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static JSONObject electronicSignatureHttpPostUtils(String queryUrl, String json) throws Exception {
        URL url = new URL(queryUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
        String date = String.valueOf(new Date().getTime());

        //3.3设置输入输出，因为默认新创建的connection没有读写权限，
        connection.setDoInput(true);
        connection.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        if (null != json) {
            outputStream.write(json.getBytes(StandardCharsets.UTF_8));
        }
        outputStream.flush();
        outputStream.close();

        // 发送请求并获取响应码
        int responseCode = connection.getResponseCode();
        String line = null;
        // 检查响应码
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 处理响应内容
            JSONObject resultJson = JSONUtil.parseObj(response.toString());
            // 关闭连接
            connection.disconnect();
            return resultJson;
        } else {
            // 处理错误响应
            throw new SecurityException("请求失败，请重试！");

        }
    }
}
